#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>

int main()
{
    pid_t child_pid;
    child_pid=fork();
    if(child_pid<0)
    {
        //进程创建失败
        perror("Fork failed\n");
    }else if(child_pid==0)
    {
        //子进程
        printf("Child process:My PID is %d\n",getpid());
        exit(0);
    }else{
        //父进程
        printf("Parent process:My PID is %d\n",getpid());
        printf("Parent process:Child PID is %d\n",child_pid);
        //Wait for child process to complete
        int status;
      // pid_t id= waitpid(child_pid,&status,0);
          printf("%d\n",waitpid(child_pid,&status,0));
      //  if(id==0){
      //      printf("Parent process:Child exit with status %d\n",id);
      //   }
           // WIFEXITED(status)：用于查看进程是否是正常退出，本质是检查是否收到信号。
           // WEXITSTATUS(status)：用于获取进程的退出码。

      // int status;
      // waitpid(child_pid, &status, 0);  // 第一次调用：正确获取子进程状态
      // 错误的代码段
      // if(waitpid(child_pid, &status, 0)) {  // 第二次调用：此时子进程已终止，返回 -1
      // printf("Parent process: Child exit with status %d\n", 
      //     waitpid(child_pid, &status, 0)); // 第三次调用：返回 -1
     }
    return 0;
}
